package logic

import (
	"context"
	"fmt"
	"seek/models/cache"
	"seek/models/mysql"

	"seek/seekrpc/internal/svc"
	"seek/seekrpc/seekrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *seekrpc.LoginRequest) (*seekrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	captcha, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if captcha != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册,不允许登录")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}
	return &seekrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
